<template>
    <v-dialog width="500" v-model="show">
        <div class="dialog-main" style="padding: 1rem">
            <div>
                <h3 style="font-weight: normal; margin: 1rem">文件夹</h3>
            </div>
            <v-row class="chips-box">
                <v-chip-group>
                    <v-chip
                            v-for="(chip, index) in foldersData"
                            :key="index"
                            @click="chipData.selectedIndex === index ? chipData.selectedIndex = -1 : chipData.selectedIndex = index"
                            class="ma-2"
                            color="primary"
                            close
                            @click:close="removeChip(index)"
                            :outlined="!(chipData.selectedIndex === index)"
                            pill
                    >
                        {{ chip.name }}
                    </v-chip>
                </v-chip-group>
                <v-menu
                        v-model="chipData.dialog"
                        :close-on-content-click="false"
                        :nudge-width="200"
                        offset-x
                >
                    <template v-slot:activator="{ on, attrs }">
                        <v-chip
                                class="ma-2"
                                color="primary"
                                outlined
                                v-bind="attrs"
                                v-on="on"
                        >
                            <v-icon left> mdi-chip</v-icon>
                            添加文件夹
                        </v-chip>
                    </template>
                    <div style="padding: 1rem">
                        <v-row class="flex justify-space-between" style="margin: 0.5rem 0">
                            <span class="blue--text"> 添加文件夹 </span>
                            <v-icon slot="append" color="red" @click="chipData.dialog = false">
                                mdi-close
                            </v-icon>
                        </v-row>

                        <v-text-field placeholder="添加文件夹" v-model="chipData.addText"/>
                        <v-btn
                                color="primary"
                                @click="addChipOne"
                                :loading="chipData.loading"
                        >
                            创建卡片目录
                        </v-btn>
                    </div>
                </v-menu>
            </v-row>

            <v-form ref="form" v-model="valid" lazy-validation>
                <v-file-input
                        accept="*/*"
                        :rules="[
            (value) => !!value || '上传的文件必须填写',
            (value) =>
              !value || value.size < 1000000 * 100 || '最大只能上传100MB',
          ]"
                        placeholder="请选择一个小于100MB的文件上传"
                        show-size
                        prepend-icon="mdi-file"
                        label="文件"
                        v-model="uploadData.uploadFile"
                ></v-file-input>
                <v-btn
                        :disabled="!valid"
                        color="primary"
                        @click="upload"
                        :loading="uploadData.loading"
                >
                    上传
                </v-btn>
                <v-progress-circular
                        :value="uploadData.progress.value"
                        style="margin-left: 1rem"
                        color="indigo darken-2"
                        v-if="uploadData.loading"
                >
                    {{ uploadData.progress.value }}
                </v-progress-circular>
            </v-form>
        </div>
    </v-dialog>
</template>

<script>
    import {_, app, db} from "../common/cloudbase";
    import {mapState} from "vuex";
    import Chips from "../common/model/Chips";

    export default {
        name: "UploadFileDialog",
        data: () => ({
            show: null,
            valid: true,
            uploadData: {
                uploadFile: null,
                progress: {
                    value: 0,
                },
                loading: false,
            },
            chipData: {
                dialog: false,
                addText: null,
                loading: false,
                selectedIndex: null,
            },
        }),
        computed: {
            ...mapState(['user','foldersData'])
        },
        methods: {
            async upload() {
                if (this.$refs.form.validate()) {
                    try {
                        let file = this.uploadData.uploadFile;
                        let user = this.user;
                        let email = user.email;
                        let chip = this.foldersData[this.chipData.selectedIndex];
                        let path = [
                            email?.replace('.', '_'),
                            chip ? chip.name : '',
                            file.name
                        ];
                        path = path.join("/").replace('//', "/");

                        this.uploadData.loading = true;
                        this.uploadData.progress.loading = true;
                        let filesCollection = db.collection("files");
                        let uploadRes = await app.uploadFile({
                            cloudPath: path,
                            filePath: file,
                            onUploadProgress: (progressEvent) => {
                                let percentCompleted = Math.round(
                                    (progressEvent.loaded * 100) / progressEvent.total
                                );
                                this.uploadData.progress.value = percentCompleted;
                            },
                        });
                        if (uploadRes) {
                            let addData = {
                                filename: file.name,
                                uploadTime: new Date(),
                                folder: chip?.name,
                                fileID: uploadRes.fileID,
                            }
                            let fileCount = await filesCollection.where({
                                fileID: _.eq(uploadRes.fileID)
                            }).count();

                            if(fileCount.total > 0){
                                alert("文件已经存在了，请删除后上传");
                                this.uploadData.loading = false;
                                this.uploadData.progress.value = 0;
                                return;
                            }

                            let fileRes = await filesCollection.add(addData);

                            if (fileRes) {
                                alert("上传成功");
                                addData._id = fileRes.id;
                                this.uploadData.uploadFile = null;
                                this.$emit("show", false);
                                this.$emit("upload", addData);
                            }
                        }
                        this.uploadData.loading = false;
                        this.uploadData.progress.value = 0;
                    } catch (err) {
                        alert("上传失败");
                        console.log(err);
                        this.uploadData.loading = false;
                        this.uploadData.progress.value = 0;
                    }
                }
            },
            /**
             * 删除一个文件夹卡片
             */
            async removeChip(index) {
                if (!confirm("是否要删除这个卡片文件夹")) return;
                try {
                    let chip = this.foldersData[index];
                    let removeRes = await Chips.remove(chip._id);
                    if (removeRes) {
                        this.foldersData.splice(index, 1);
                    }
                } catch (err) {
                    alert("删除失败");
                }
            },
            /**
             * 添加一个文件夹卡片
             */
            async addChipOne() {
                this.chipData.loading = true;
                let txt = this.chipData.addText;
                if (!txt) {
                    alert("你还没有填写数据");
                    this.chipData.loading = false;
                    return;
                }
                try {
                    let addRes = await Chips.add(txt);
                    if (addRes) {
                        this.foldersData.push(addRes);
                        this.chipData.addText = null;
                        this.chipData.dialog = false;
                        this.chipData.loading = false;
                        alert("添加成功");
                        return;
                    }
                    this.chipData.loading = false;
                } catch (err) {
                    alert("添加失败");
                    this.chipData.loading = false;
                }
            },
        },
        mounted() {

        },
        model: {
            prop: "dialog",
            event: "show",
        },
        props: {
            dialog: Boolean,
        },
        watch: {
            show(v) {
                this.$emit("show", v);
            },
            dialog: {
                handler(v) {
                    this.$emit("show", v);
                    this.show = v;
                },
                immediate: true,
            },
        },
    };
</script>

<style scoped lang="scss">
    .dialog-main {
        .chips-box {
            display: flex;
            margin: 1rem 0;
        }

        /*width: 90%;*/
        /*max-width: 50rem;*/
    }
</style>